package com.uduemc.biso.node.web.service.impl;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
import com.uduemc.biso.core.extities.pojo.ICP35;
import com.uduemc.biso.core.utils.CryptoJava;
import com.uduemc.biso.node.core.entities.HConfig;
import com.uduemc.biso.node.core.entities.HDomain;
import com.uduemc.biso.node.web.component.RequestHolder;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.config.SpringContextUtil;
import com.uduemc.biso.node.web.service.HBodyAfterService;
import com.uduemc.biso.node.web.service.SeoCodeService;
import com.uduemc.biso.node.web.service.byfeign.DeployService;
import com.uduemc.biso.node.web.service.byfeign.LanguageService;

import cn.hutool.core.util.StrUtil;

@Service
public class HBodyAfterServiceImpl implements HBodyAfterService {

	@Autowired
	private SeoCodeService seoCodeServiceImpl;

	@Autowired
	private RequestHolder requestHolder;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	@Autowired
	private SpringContextUtil springContextUtil;

	@Autowired
	private DeployService deployServiceImpl;

	@Autowired
	private VelocityEngine velocityEngine;

	@Autowired
	private HtmlCompressor htmlCompressor;

	@Autowired
	private LanguageService languageServiceImpl;

	@Override
	public StringBuilder html() throws IOException {
		// 底部增加 lingthbox 插件
		StringBuilder html = new StringBuilder("\n<!-- after body -->");

		html.append("\n<link href=\"" + siteUrlComponent.getSourcePath("/assets/static/site/public/plugins/lightbox/css/lightbox.min.css")
				+ "\" rel=\"stylesheet\" />");
		html.append("\n<script type=\"text/javascript\" src=\""
				+ siteUrlComponent.getSourcePath("/assets/static/site/public/plugins/lightbox/js/lightbox.min.js") + "\"></script>");

		long pageId = requestHolder.getPageId();
		String pEncode = String.valueOf(pageId);
		String pfxEncode = "";
		String pfxhfEncode = "";
		try {
			pEncode = CryptoJava.en(String.valueOf(pageId));
			pfxEncode = CryptoJava.en(siteUrlComponent.prefix());
			pfxhfEncode = CryptoJava.en(siteUrlComponent.prefixHref(languageServiceImpl.getLanNoBySite(requestHolder.getSite())));
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		String surfaceSrc = "/assets/dynamic/data/surface.js?p=" + pEncode + "&pfx=" + pfxEncode + "&pfxhf=" + pfxhfEncode + "&v="
				+ requestHolder.getAccessHost().getHostConfig().getPublish();
		String sourcePath = siteUrlComponent.getSourcePath(surfaceSrc);
		// 动态的 surface 数据
		html.append("\n<script type=\"text/javascript\" src=\"" + sourcePath + "\"></script>");

		if (springContextUtil.local()) {
			html.append("\n<script type=\"text/javascript\" src=\"http://localhost:2388/sitejs.js\"></script>");
		} else {
			String sitejsVersion = deployServiceImpl.siteJsVersion();
			String sitejs = siteUrlComponent.getSourcePath("/assets/deploy/site/sitejs.js?v=" + sitejsVersion);
			html.append("\n<script type=\"text/javascript\" src=\"" + sitejs + "\"></script>");
		}

		String beforeEndBody = seoCodeServiceImpl.beforeEndBody();
		html.append(beforeEndBody);

		return html;
	}

	@Override
	public StringBuilder searchHtml() throws IOException {
		// 底部增加 lingthbox 插件
		StringBuilder html = new StringBuilder("\n<!-- after body -->");

		html.append("\n<link href=\"" + siteUrlComponent.getSourcePath("/assets/static/site/public/plugins/lightbox/css/lightbox.min.css")
				+ "\" rel=\"stylesheet\" />");
		html.append("\n<script type=\"text/javascript\" src=\""
				+ siteUrlComponent.getSourcePath("/assets/static/site/public/plugins/lightbox/js/lightbox.min.js") + "\"></script>");

		html.append("\n<script type=\"text/javascript\" src=\"" + siteUrlComponent.getSourcePath("/assets/static/site/public/js/jquery.search.js")
				+ "\"></script>");

		// -1 标识 /search.html 页面
		long pageId = -1;
		long siteId = requestHolder.getSiteId();
		String pEncode = String.valueOf(pageId);
		String sEncode = String.valueOf(siteId);
		String pfxEncode = "";
		String pfxhfEncode = "";
		try {
			pEncode = CryptoJava.en(String.valueOf(pageId));
			sEncode = CryptoJava.en(String.valueOf(siteId));
			pfxEncode = CryptoJava.en(siteUrlComponent.prefix());
			pfxhfEncode = CryptoJava.en(siteUrlComponent.prefixHref(languageServiceImpl.getLanNoBySite(requestHolder.getSite())));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String surfaceSrc = "/assets/dynamic/data/surface.js?p=" + pEncode + "&s=" + sEncode + "&pfx=" + pfxEncode + "&pfxhf=" + pfxhfEncode + "&v="
				+ requestHolder.getAccessHost().getHostConfig().getPublish();
		String sourcePath = siteUrlComponent.getSourcePath(surfaceSrc);
		// 动态的 surface 数据
		html.append("\n<script type=\"text/javascript\" src=\"" + sourcePath + "\"></script>");

		if (springContextUtil.local()) {
			html.append("\n<script type=\"text/javascript\" src=\"http://localhost:2388/sitejs.js\"></script>");
		} else {
			String sitejsVersion = deployServiceImpl.siteJsVersion();
			String sitejs = siteUrlComponent.getSourcePath("/assets/deploy/site/sitejs.js?v=" + sitejsVersion);
			html.append("\n<script type=\"text/javascript\" src=\"" + sitejs + "\"></script>");
		}

		String beforeEndBody = seoCodeServiceImpl.searchPageBeforeEndBody();
		html.append(beforeEndBody);

		return html;
	}

	@Override
	public StringBuilder webSiteConfig() throws IOException {
		HConfig hostConfig = requestHolder.getAccessHost().getHostConfig();
		StringBuilder result = new StringBuilder();

		StringBuilder disabledRightClick = disabledRightClick(hostConfig);
		if (StrUtil.isNotBlank(disabledRightClick)) {
			result.append(disabledRightClick);
		}

		StringBuilder disabledCopyPaste = disabledCopyPaste(hostConfig);
		if (StrUtil.isNotBlank(disabledCopyPaste)) {
			result.append(disabledCopyPaste);
		}

		StringBuilder disabledF12 = disabledF12(hostConfig);
		if (StrUtil.isNotBlank(disabledF12)) {
			result.append(disabledF12);
		}

		return result;
	}

	protected StringBuilder disabledF12(HConfig hostConfig) {
		if (hostConfig == null) {
			return null;
		}
		Short disabledF12 = hostConfig.getDisabledF12();
		if (disabledF12 != null && disabledF12.shortValue() == (short) 1) {
			Template template = velocityEngine.getTemplate("templates/javascript/disabled_f12.vm");
			StringWriter sw = new StringWriter();
			template.merge(null, sw);
			return new StringBuilder("\n" + htmlCompressor.compress(sw.toString()));
		}
		return null;
	}

	protected StringBuilder disabledCopyPaste(HConfig hostConfig) {
		if (hostConfig == null) {
			return null;
		}
		Short disabledCopyPaste = hostConfig.getDisabledCopyPaste();
		if (disabledCopyPaste != null && disabledCopyPaste.shortValue() == (short) 1) {
			Template template = velocityEngine.getTemplate("templates/javascript/disabled_copy_paste.vm");
			StringWriter sw = new StringWriter();
			template.merge(null, sw);
			return new StringBuilder("\n" + htmlCompressor.compress(sw.toString()));
		}
		return null;
	}

	protected StringBuilder disabledRightClick(HConfig hostConfig) {
		if (hostConfig == null) {
			return null;
		}
		Short disabledRightClick = hostConfig.getDisabledRightClick();
		if (disabledRightClick != null && disabledRightClick.shortValue() == (short) 1) {
			Template template = velocityEngine.getTemplate("templates/javascript/disabled_right_click.vm");
			StringWriter sw = new StringWriter();
			template.merge(null, sw);
			return new StringBuilder("\n" + htmlCompressor.compress(sw.toString()));
		}
		return null;
	}

	@Override
	public StringBuilder webSiteRecord() throws IOException {
		HConfig hostConfig = requestHolder.getAccessHost().getHostConfig();
		HDomain hDomain = requestHolder.getAccessHost().getHDomain();

		StringBuilder result = new StringBuilder();

		Short webRecord = hostConfig.getWebRecord();
		webRecord = webRecord == null ? (short) 0 : webRecord.shortValue();
		if (webRecord.shortValue() == (short) 0) {
			return result;
		}

		String policeRecordText = "";
		String webRecordText = "";
		String policeRecordNumberText = "";
		strFindNumber(policeRecordText);
		if (hDomain != null) {
			String policeRecord = hDomain.getPoliceRecord();
			if (StrUtil.isNotBlank(policeRecord)) {
				policeRecordText = policeRecord;
			}
			String remark = hDomain.getRemark();
			ICP35 icp = ICP35.makeICP35(remark);
			webRecordText = icp.getSiteinfo();
			policeRecordNumberText = strFindNumber(policeRecordText);
		}

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("webRecordText", webRecordText);
		mapData.put("policeRecordText", policeRecordText);
		mapData.put("policeRecordNumberText", policeRecordNumberText);

		VelocityContext ctx = new VelocityContext(mapData);
		Template template = velocityEngine.getTemplate("templates/html/record.vm");
		StringWriter sw = new StringWriter();
		template.merge(ctx, sw);
		result.append("\n" + htmlCompressor.compress(sw.toString()));

		return result;
	}

	public static String strFindNumber(String a) {
		String regEx = "[^0-9]";
		Matcher matcher = Pattern.compile(regEx).matcher(a);
		String trim = matcher.replaceAll("").trim();
		return trim;
	}

}
